<template>
  <div class="profile-container el-row">

    <!-- 右侧内容区域 - 调整栅格占据整个宽度 -->
    <el-col :xs="24" :sm="24" :md="24" class="profile-content">
      <div v-if="loadingProfile" class="loading-state">
        <el-skeleton :rows="5" animated />
      </div>
      <template v-else>
        <!-- 用户基本信息区域 -->
        <div class="user-info-section">
          <div class="user-avatar-container">
            <el-avatar :size="100" :src="targetUser?.avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-upload
              v-if="isCurrentUser"
              class="avatar-uploader"
              action="/api/users/avatar"
              :headers="{ Authorization: `Bearer ${token}` }"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <el-button size="small" type="primary" class="upload-btn">更换头像</el-button>
            </el-upload>
          </div>
          <div class="user-details">
            <div class="username-container">
              <h2 class="username">{{ targetUser?.username || '用户名' }}</h2>
              <el-button 
                v-if="isCurrentUser" 
                size="small" 
                type="primary" 
                @click="showEditForm = true"
                class="edit-profile-btn">
                编辑资料
              </el-button>
            </div>
            <p class="user-bio">{{ targetUser?.bio || '这个用户很懒，还没有填写个人简介' }}</p>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-value">{{ totalVideos }}</span>
                <span class="stat-label">视频</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ targetUser?.followersCount || 0 }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ targetUser?.followingCount || 0 }}</span>
                <span class="stat-label">关注</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 编辑个人资料表单 -->
        <el-dialog
          v-model="showEditForm"
          title="编辑个人资料"
          width="500px">
          <el-form :model="profileForm" label-width="80px">
            <el-form-item label="用户名">
              <el-input v-model="profileForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="个人简介">
              <el-input 
                v-model="profileForm.bio" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入个人简介"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="profileForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showEditForm = false">取消</el-button>
              <el-button type="primary" @click="updateProfile" :loading="updating">
                保存
              </el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 内容区域 -->
        <div class="content-wrapper">
          <!-- 默认显示我的视频 -->
          <div>
            <h3>我的视频</h3>
            <div v-if="loadingVideos" class="loading-state">
              <el-skeleton :rows="3" animated />
            </div>
            <div v-else-if="userVideos.length === 0" class="empty-state">
              <el-empty description="你还没有上传任何视频" />
            </div>
            <div v-else class="video-list">
              <div class="video-grid">
                <VideoCard
                  v-for="video in userVideos"
                  :key="video._id"
                  :video="video"
                />
              </div>
              <el-pagination
                v-if="totalVideos > videoPageSize"
                layout="prev, pager, next"
                :total="totalVideos"
                :page-size="videoPageSize"
                :current-page="videoPage"
                @current-change="handleVideoPageChange"
              />
            </div>
          </div>
        </div>
      </template>
    </el-col>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue';
import { ElMessage, ElSkeleton, ElEmpty, ElPagination, ElAvatar, ElUpload, ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus'; // 添加新组件导入
// 移除不再需要的图标导入
// import { VideoCamera, Document } from '@element-plus/icons-vue';
import axios from '@/services/axios';
import { useStore } from 'vuex';
import VideoCard from '@/components/VideoCard.vue'; // 假设有 VideoCard 组件

const store = useStore();
const user = computed(() => store.getters['auth/user']);
const userId = computed(() => store.getters['auth/userId']);
const token = computed(() => store.getters['auth/token']); // 获取token用于头像上传

// 获取目标用户信息
const targetUser = ref(null);

// 判断是否为当前登录用户的个人资料
const isCurrentUser = computed(() => {
  const targetUserId = route.params.userId || userId.value;
  return userId.value && targetUserId === userId.value;
});

// 监听路由参数变化，加载目标用户信息
watch(
  () => route.params.userId,
  async (newRouteUserId) => {
    const targetUserIdToLoad = newRouteUserId || userId.value;
    
    if (targetUserIdToLoad) {
      loadingProfile.value = true;
      try {
        // 如果是查看自己的主页，直接使用 store 中的用户信息
        if (targetUserIdToLoad === userId.value && user.value && !newRouteUserId) {
          targetUser.value = user.value;
        } else {
          // 获取其他用户或强制刷新自己的信息
          const response = await axios.get(`/api/users/${targetUserIdToLoad}`);
          if (response.data && response.data.user) {
            targetUser.value = response.data.user;
          } else {
            throw new Error('获取用户信息失败');
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败');
        targetUser.value = null; // 获取失败时清空用户信息
      } finally {
        loadingProfile.value = false;
      }

      // 加载用户视频
      if (targetUser.value) {
        await fetchUserVideos(targetUser.value._id);
      } else {
        userVideos.value = [];
        totalVideos.value = 0;
      }
    }
  },
  { immediate: true }
);

// 在模板中使用 targetUser 替代 user
// 例如：{{ targetUser?.username || '用户名' }}

// 加载状态
const loadingProfile = ref(false);
const loadingVideos = ref(false);
const updating = ref(false); // 更新个人资料的加载状态

// 编辑表单相关
const showEditForm = ref(false);
const profileForm = reactive({
  username: '',
  bio: '',
  email: ''
});

// 初始化表单数据
const initProfileForm = () => {
  if (targetUser.value) {
    profileForm.username = targetUser.value.username || '';
    profileForm.bio = targetUser.value.bio || '';
    profileForm.email = targetUser.value.email || '';
  }
};

// 监听目标用户信息变化，更新表单
watch(
  () => targetUser.value,
  () => {
    if (isCurrentUser.value) {
      initProfileForm();
    }
  }
);

// 更新个人资料
const updateProfile = async () => {
  if (!userId.value) return;
  updating.value = true;
  try {
    const response = await axios.put(`/api/users/profile`, profileForm);
    await store.dispatch('auth/getProfile'); // 重新获取用户信息
    ElMessage.success('个人资料更新成功');
    showEditForm.value = false;
  } catch (error) {
    console.error('更新个人资料失败:', error);
    ElMessage.error('更新个人资料失败');
  } finally {
    updating.value = false;
  }
};

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是JPG或PNG格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB!');
    return false;
  }
  return true;
};

// 头像上传成功的回调
const handleAvatarSuccess = async (response) => {
  if (response.success) {
    await store.dispatch('auth/getProfile'); // 重新获取用户信息
    ElMessage.success('头像更新成功');
  } else {
    ElMessage.error('头像更新失败');
  }
};

// 视频分页
const userVideos = ref([]);
const totalVideos = ref(0);
const videoPage = ref(1);
const videoPageSize = ref(12);

// 获取用户视频
const fetchUserVideos = async (targetUserId) => {
  if (!targetUserId) return;
  loadingVideos.value = true;
  try {
    const response = await axios.get(`/api/users/${targetUserId}/videos`, {
      params: {
        page: videoPage.value,
        limit: videoPageSize.value
      }
    });
    userVideos.value = response.data.videos;
    totalVideos.value = response.data.total;
  } catch (error) {
    console.error('获取用户视频失败:', error);
    ElMessage.error('获取用户视频失败');
  } finally {
    loadingVideos.value = false;
  }
};

// 视频页码变化
const handleVideoPageChange = (newPage) => {
  videoPage.value = newPage;
  // 使用路由参数中的用户ID或当前用户ID
  const targetUserId = route.params.userId || userId.value;
  fetchUserVideos(targetUserId);
};

// 导入 useRoute
import { useRoute } from 'vue-router';

// 获取路由实例
const route = useRoute();

// 组件挂载时
onMounted(async () => {
  // 从路由参数获取用户ID，如果没有则使用当前用户的ID
  const currentRouteUserId = route.params.userId;
  const targetUserIdToLoad = currentRouteUserId || userId.value;

  // 确保当前登录用户信息已加载 (如果需要显示当前用户信息)
  if (!user.value && userId.value && !currentRouteUserId) { // 仅当查看自己且用户信息未加载时
    loadingProfile.value = true;
    try {
      await store.dispatch('auth/getProfile');
      // dispatch 后 user.value 会更新，如果 targetUser 依赖它，需要在这里或 watch 中处理
    } catch (error) {
      ElMessage.error('获取当前用户信息失败');
    } finally {
      loadingProfile.value = false;
    }
  }

  // 监听路由参数变化
  watch(
    () => route.params.userId,
    async (newRouteUserId) => {
      const targetUserIdToLoad = newRouteUserId || userId.value;
      
      // 加载目标用户信息
      if (targetUserIdToLoad) {
        loadingProfile.value = true;
        try {
          // 如果是查看自己且 user.value 已有数据，则直接使用，避免重复请求
          if (targetUserIdToLoad === userId.value && user.value && !newRouteUserId) { // 确保是导航到自己且 user.value 存在
            targetUser.value = user.value;
          } else {
            const response = await axios.get(`/api/users/${targetUserIdToLoad}`);
            targetUser.value = response.data.user;
          }
        } catch (error) {
          console.error('获取目标用户信息失败:', error);
          ElMessage.error('获取目标用户信息失败');
          targetUser.value = null; // 获取失败时清空
        } finally {
          loadingProfile.value = false;
        }
      }
  
      // 重置页码并加载视频数据 (依赖 targetUser)
      videoPage.value = 1; 
      if (targetUser.value) {
        await fetchUserVideos(targetUser.value._id);
      } else {
        // 如果 targetUser 获取失败，清空视频列表
        userVideos.value = [];
        totalVideos.value = 0;
      }
    }
  );
});



// 监听路由参数变化
watch(
  () => route.params.userId,
  (newUserId) => {
    const targetUserId = newUserId || userId.value;
    videoPage.value = 1; // 重置页码
    fetchUserVideos(targetUserId);
  }
);</script>

<style scoped>
/* 样式基本保持不变，移除侧边栏相关样式 */
.profile-container {
  min-height: calc(100vh - 56px); /* 调整高度以适应布局 */
  background-color: #f5f7fa;
  padding: 20px;
}

.profile-menu .el-menu-item.is-active {
  background-color: #e6f4ff;
  color: #1890ff;
}

.profile-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 用户信息区域样式 */
.user-info-section {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e5e5;
}

.user-avatar-container {
  margin-right: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader {
  margin-top: 10px;
}

.upload-btn {
  margin-top: 8px;
  font-size: 12px;
}

.user-details {
  flex: 1;
}

.username-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.edit-profile-btn {
  margin-left: 15px;
  font-size: 12px;
}

.username {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #0f0f0f;
}

.user-bio {
  color: #606060;
  margin: 0 0 15px 0;
  font-size: 14px;
  max-width: 600px;
}

.user-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #0f0f0f;
}

.stat-label {
  font-size: 12px;
  color: #606060;
}

.loading-state,
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px; /* 保证有最小高度 */
  color: #909399;
}

.content-wrapper h3 {
  font-size: 20px;
  font-weight: 500;
  color: #0f0f0f;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e5e5;
}

.video-list,
.post-list { /* post-list 样式暂时保留，以防后续需要 */
  margin-top: 20px;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* 调整最小宽度 */
  gap: 20px;
  margin-bottom: 20px;
}

.post-item-placeholder { /* 暂时保留 */
  padding: 15px;
  border: 1px solid #eee;
  margin-bottom: 10px;
  border-radius: 4px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }

  .profile-content {
    padding: 20px;
  }
  
  .user-info-section {
    flex-direction: column;
    text-align: center;
  }
  
  .user-avatar-container {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .username-container {
    justify-content: center;
  }
  
  .user-stats {
    justify-content: center;
  }
  
  .video-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}
</style>
